package cn.seqdata.cxf.oauth2;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.rs.security.oauth2.common.Client;
import org.apache.cxf.rs.security.oauth2.common.UserSubject;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class JdbcSubjectStore extends JdbcDaoSupport implements SubjectStore {
	private String tblSubject = "account_info";
	private String keySubject = "id";
	private String valSubject = "password";
	private final Set<String> keys = new HashSet<>(Arrays.asList("username", "mobile", "email"));

	@Override
	public Client selectClient(String clientId) {
		if(StringUtils.isBlank(clientId))
			return null;

		for(String key : keys) {
			String sql = String.format("select %s,%s from %s where %s=?", getKeySubject(), getValSubject(),
				getTblSubject(), key);
			try {
				return getJdbcTemplate().queryForObject(sql, (rs, rowNum) -> {
					String subjectId = rs.getString(getKeySubject());
					String password = rs.getString(getValSubject());

					Client client = new Client(clientId, password, true);
					UserSubject subject = new UserSubject(clientId, subjectId);
					processSubject(subject);
					client.setResourceOwnerSubject(subject);

					return client;
				}, clientId);
			} catch(EmptyResultDataAccessException ex) {
			}
		}
		return null;
	}

	public String getTblSubject() {
		return tblSubject;
	}

	public void setTblSubject(String tblSubject) {
		this.tblSubject = tblSubject;
	}

	public String getKeySubject() {
		return keySubject;
	}

	public void setKeySubject(String keySubject) {
		this.keySubject = keySubject;
	}

	public String getValSubject() {
		return valSubject;
	}

	public void setValSubject(String valSubject) {
		this.valSubject = valSubject;
	}

	protected Set<String> getKeys() {
		return keys;
	}
}
